package com.zrf.testchatgpt.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import com.zrf.testchatgpt.service.IConfigService;
import com.zrf.testchatgpt.translate.demo.TransApi;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



import java.io.UnsupportedEncodingException;

import java.net.URLDecoder;

import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
@Component
public class TranslateUtil {
    @Autowired
    IConfigService iSysConfigService;

    public Map<String,Object> toTranslate( Map<String, Object> map)  {

        String appid = iSysConfigService.selectConfigByKey("baidu_appid");
        String secret = iSysConfigService.selectConfigByKey("baidu_secret");
        TransApi api = new TransApi(appid,secret);
        //创建线程池，核心线程1，最大线程数10，存货时间1分钟，任务队列5，默认的线程工厂，拒绝策略为拒绝并抛出异常
        ExecutorService executorService = new ThreadPoolExecutor(1, 10, 1, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(5, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        for (String key : map.keySet()) {
            Object childMap = map.get(key);
            StringBuilder builder = new StringBuilder();
            //需要翻译的中文
            builder.append(childMap).append("\n");
            //执行线程
            executorService.execute(() -> {
                String result = api.getTransResult(builder.toString(), "auto", "en");
                System.out.println("result:" + result);
                //转成map
                Map<String, String> mapResult = JSON.parseObject(result, Map.class);
                List<Map<String, String>> transResult = (List<Map<String, String>> ) JSONArray.parse(JSON.toJSONString(mapResult.get("trans_result")));
                //获取翻译结果
                String transQuery = (String) transResult.get(0).get("dst");
                try {
                    //解码
                    transQuery = URLDecoder.decode(transQuery, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                map.put(key, transQuery);
            });
            //线程池等待时间，这里即阻塞2秒
            try {
                executorService.awaitTermination(1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //任务执行完成后关闭线程池
        executorService.shutdown();
        return map;
    }


}
